<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import apiUser from '@/api/modules/userMange'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'RanksEdit',
})
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const updateImg = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')

// 学校类
interface SchoolOption {
  label: string
  value: number
}

// 角色类
interface RoleOption {
  label: string
  value: number
}

const schoolOptions = ref<SchoolOption[]>([]) // 加载学校列表
const RoleOptions = ref<RoleOption[]>([]) // 加载角色列表
const RanksOptions = ref([
  { label: '无', value: 0 },
  { label: '校园大使', value: 1 },
])
const form = ref({
  userId: route.params.id as string | number ?? '',
  nickName: '',
  phonenumber: '',
  avatar: '',
  sex: '',
  status: '',
  password: '',
  schoolId: -1, // 学校id
  ranks: '', // 头衔
  briefIntroduction: '', // 简介
  designer: '', // 描述
  imagePhoto: '',
  roleId: '',
  briefIntroductionEn: '',
})
const formRules = ref<FormRules>({
  nickName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  phonenumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  avatar: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
  schoolId: [ // 新增
    { required: true, message: '请输入学校ID', trigger: 'blur' },
  ],
  ranks: [ // 新增
    { required: true, message: '请输入头衔', trigger: 'blur' },
  ],
  briefIntroduction: [ // 新增
    { required: true, message: '请输入简介', trigger: 'blur' },
  ],
  designer: [ // 新增
    { required: true, message: '请输入设计师', trigger: 'blur' },
  ],
  // imagePhoto: [ // 新增
  //   { required: true, message: '请上传图片', trigger: 'blur' },
  // ],
})

onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadSchoolOptions(),
      loadRoleOptions(),
    ])
    if (form.value.userId !== '') {
      await getInfo()
    }
  }
  catch (error) {
    console.error('加载失败', error)
    ElMessage.error('数据加载失败')
  }
  finally {
    loading.value = false
  }
})

async function getInfo() {
  try {
    const res: any = await apiUser.detail(form.value.userId) // 明确类型断言
    form.value.nickName = res.data.nickName
    form.value.phonenumber = res.data.phonenumber
    form.value.avatar = res.data.avatar
    form.value.sex = res.data.sex
    form.value.status = res.data.status
    form.value.schoolId = Number(res.data.schoolId)
    form.value.ranks = res.data.ranks
    form.value.briefIntroduction = res.data.briefIntroduction
    form.value.designer = res.data.designer
    form.value.imagePhoto = res.data.imagePhoto
    form.value.roleId = res.data.roleId
  }
  finally {
    loading.value = false
  }
  // 无需 finally，loading 由外层控制
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        if (form.value.userId === '') {
          apiUser.create(form.value).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.userId = Number(form.value.userId)
          apiUser.edit(form.value).then(() => {
            console.log('form.value=', form.value)
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}

async function handleSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiUser.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.avatar = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
async function handleSuccessimagePhoto(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiUser.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.imagePhoto = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}

// 获取学校列表
async function loadSchoolOptions() {
  try {
    const res = await apiUser.getSchoolList()
    schoolOptions.value = res.data.map((item: any) => ({
      label: item.schoolName,
      value: item.schoolId,
    }))
  }
  catch (error) {
    console.error('加载失败', error)
  }
}

// 获取用户列表
async function loadRoleOptions() {
  try {
    const res = await apiUser.getRoleList()

    RoleOptions.value = res.data.map((item: any) => ({
      label: item.roleName,
      value: item.roleId,
    }))
  }
  catch (error) {
    console.error('加载失败', error)
  }
}

function onCancel() {
  goBack()
}

// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'userManagement' })
  }
  else {
    router.push({ name: 'userManagement' })
  }
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'userManagementCreate' ? '新增用户' : '编辑信息'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm
      ref="formRef"
      v-loading="loading"
      :model="form"
      :rules="formRules"
      label-width="120px"
      label-suffix="："
      class="custom-form"
      element-loading-text="数据加载中..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <FaLayoutContainer
        right-side-width="500px" hide-right-side-toggle class="static"
        right-side-class="flex flex-col"
      >
        <ElFormItem label="用户名称" prop="nickName">
          <ElInput v-model="form.nickName" placeholder="请输入用户名称" />
        </ElFormItem>

        <ElFormItem label="手机号码" prop="phonenumber">
          <ElInput v-model="form.phonenumber" placeholder="请输入手机号" />
        </ElFormItem>
        <ElFormItem label="帐号状态" prop="status">
          <ElSwitch
            v-model="form.status" inline-prompt active-text="启用" inactive-text="停用" active-value="0"
            inactive-value="1"
          />
        </ElFormItem>
        <ElFormItem label="上传头像" prop="avatar">
          <ImageUpload
            v-model="form.avatar" :loading="updateImg" action="" name="image" :width="150" :height="150"
            :http-request="handleSuccess"
          />
        </ElFormItem>
        <ElFormItem label="用户性别" prop="sex">
          <ElRadioGroup v-model="form.sex">
            <ElRadioButton value="2">
              保密
            </ElRadioButton>
            <ElRadioButton value="0">
              男
            </ElRadioButton>
            <ElRadioButton value="1">
              女
            </ElRadioButton>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem v-if="form.userId === ''" label="设置密码" prop="password">
          <ElInput v-model="form.password" type="password" placeholder="请输入密码" />
        </ElFormItem>
        <ElFormItem label="所属学校" prop="schoolId">
          <el-select v-model="form.schoolId" filterable placeholder="请选择学校">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </ElFormItem>
        <ElFormItem label="角色" prop="roleId">
          <el-select v-model="form.roleId" filterable placeholder="请选择角色">
            <el-option
              v-for="item in RoleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </ElFormItem>
        <ElFormItem label="简介" prop="briefIntroduction">
          <ElInput v-model="form.briefIntroduction" placeholder="请输入简介" />
        </ElFormItem>
        <ElFormItem label="头衔" prop="ranks">
          <el-select v-model="form.ranks" placeholder="请选择头衔">
            <el-option
              v-for="item in RanksOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </ElFormItem>
        <ElFormItem label="图片" prop="imagePhoto">
          <ImageUpload
            v-model="form.imagePhoto" :loading="updateImg" action="" name="imagePhoto" :width="150" :height="150"
            :http-request="handleSuccessimagePhoto"
          />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.el-form {
  display: flex;
  flex: 1;
  overflow: auto;
}

.label-tip {
  display: inline-flex;
  margin-left: 10px;
  color: var(--el-text-color-disabled);
}

.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
